package v.e.fasterbuilder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.io.*;

@Component
public class MvnInstallTask  {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${fasterbuilder.mvn_path}")
    private String mvnPath;

    @Value("${fasterbuilder.settings_path}")
    private String mvnSettingsPath;




    @Bean
    @Scope("prototype")
    public MyTask getMvnInstallTask(){
        return new MyTask() {

            private String path;

            @Override
            public void setPath(String path) {
                this.path = path;
            }


            @Override
            public void run() {
                long start = System.currentTimeMillis();
                String[] cmdarr = {"cmd", "/c", String.format("%s\\bin\\mvn", mvnPath)
                        , "clean"
                        , "package"
                        ,"-f"
                        ,String.format("%s\\pom.xml",this.path)
                        ,"-s"
                        ,mvnSettingsPath
                };
                ProcessBuilder processBuilder = new ProcessBuilder(cmdarr);
                //processBuilder.directory(new File(this.path));
                processBuilder.redirectErrorStream(true);
                try {
                    Process process = processBuilder.start();
                    InputStream is = process.getInputStream();
                    InputStreamReader isr = new InputStreamReader(is,"gbk");
                    BufferedReader br = new BufferedReader(isr);
                    String line;
                    while ((line = br.readLine()) != null)
                    {
                        logger.info(line);
                    }
                    process.waitFor();
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    long end = System.currentTimeMillis();
                    logger.info("Task1 finished, time elapsed: {} ms.", end-start);
                }
            }
        };
    }
}
